import { NextRequest, NextResponse } from "next/server"
import * as fs from "fs"
import * as path from "path"

export const dynamic = "force-dynamic"

const AGENT_DIR = path.join(process.cwd(), "data", "agent-manage")

// 确保基础目录存在
function ensureBaseDirectoryExists() {
  if (!fs.existsSync(AGENT_DIR)) {
    fs.mkdirSync(AGENT_DIR, { recursive: true })
  }
}

// 获取日期目录名：2025_10_06
function getDateDirName(date?: string): string {
  const dateStr = date || new Date().toISOString().split("T")[0]
  return dateStr.replace(/-/g, "_")
}

// 确保日期目录存在
function ensureDateDirectoryExists(dateDir: string) {
  const fullPath = path.join(AGENT_DIR, dateDir)
  if (!fs.existsSync(fullPath)) {
    fs.mkdirSync(fullPath, { recursive: true })
  }
}

// 生成文件名：只用 Agent 名称
function generateFileName(name: string): string {
  // 清理文件名中的特殊字符
  const safeName = name.replace(/[/\\?%*:|"<>]/g, "-")
  return `${safeName}.json`
}

// 获取所有日期目录
function getAllDateDirectories(): string[] {
  ensureBaseDirectoryExists()
  const items = fs.readdirSync(AGENT_DIR)
  return items.filter((item) => {
    const fullPath = path.join(AGENT_DIR, item)
    return fs.statSync(fullPath).isDirectory()
  })
}

// GET - 获取所有 Agents 或单个 Agent
export async function GET(request: NextRequest) {
  try {
    ensureBaseDirectoryExists()

    const searchParams = request.nextUrl.searchParams
    const id = searchParams.get("id")

    // 如果提供了 ID，返回单个 Agent
    if (id) {
      const dateDirs = getAllDateDirectories()

      for (const dateDir of dateDirs) {
        const dirPath = path.join(AGENT_DIR, dateDir)
        const files = fs.readdirSync(dirPath)
        const jsonFiles = files.filter((f) => f.endsWith(".json"))

        for (const file of jsonFiles) {
          const filePath = path.join(dirPath, file)
          const content = fs.readFileSync(filePath, "utf-8")
          const agent = JSON.parse(content)

          if (agent.id === id) {
            return NextResponse.json({
              success: true,
              data: agent,
            })
          }
        }
      }

      return NextResponse.json(
        { success: false, error: "Agent not found" },
        { status: 404 },
      )
    }

    // 返回所有 Agents
    const agents: any[] = []
    const dateDirs = getAllDateDirectories()

    for (const dateDir of dateDirs) {
      const dirPath = path.join(AGENT_DIR, dateDir)
      const files = fs.readdirSync(dirPath)
      const jsonFiles = files.filter((f) => f.endsWith(".json"))

      for (const file of jsonFiles) {
        const filePath = path.join(dirPath, file)
        const content = fs.readFileSync(filePath, "utf-8")
        agents.push(JSON.parse(content))
      }
    }

    // 按更新时间倒序排序
    agents.sort((a, b) => {
      const dateA = new Date(a.updatedAt || a.createdAt).getTime()
      const dateB = new Date(b.updatedAt || b.createdAt).getTime()
      return dateB - dateA
    })

    return NextResponse.json({
      success: true,
      data: agents,
    })
  } catch (error) {
    console.error("Error reading agents:", error)
    return NextResponse.json(
      { success: false, error: "Failed to read agents" },
      { status: 500 },
    )
  }
}

// POST - 创建新 Agent
export async function POST(request: NextRequest) {
  try {
    ensureBaseDirectoryExists()

    const body = await request.json()
    const { name, components, edges } = body

    if (!name) {
      return NextResponse.json(
        { success: false, error: "Agent name is required" },
        { status: 400 },
      )
    }

    const agentId = `agent_${Date.now()}`
    const now = new Date().toISOString().split("T")[0]

    const agentData = {
      id: agentId,
      name,
      components: components || [],
      edges: edges || [],
      status: "draft",
      lastRun: "从未运行",
      createdAt: now,
      updatedAt: now,
    }

    // 创建日期目录
    const dateDir = getDateDirName(now)
    ensureDateDirectoryExists(dateDir)

    // 保存文件
    const fileName = generateFileName(name)
    const filePath = path.join(AGENT_DIR, dateDir, fileName)

    fs.writeFileSync(filePath, JSON.stringify(agentData, null, 2), "utf-8")

    return NextResponse.json({
      success: true,
      data: agentData,
      message: "Agent created successfully",
    })
  } catch (error) {
    console.error("Error creating agent:", error)
    return NextResponse.json(
      { success: false, error: "Failed to create agent" },
      { status: 500 },
    )
  }
}

// PUT - 更新 Agent
export async function PUT(request: NextRequest) {
  try {
    ensureBaseDirectoryExists()

    const body = await request.json()
    const { id, name, components, edges } = body

    if (!id) {
      return NextResponse.json(
        { success: false, error: "Agent ID is required" },
        { status: 400 },
      )
    }

    const dateDirs = getAllDateDirectories()
    let found = false
    let oldFilePath = ""
    let oldDateDir = ""
    let agentData: any = null

    // 查找现有 Agent
    for (const dateDir of dateDirs) {
      const dirPath = path.join(AGENT_DIR, dateDir)
      const files = fs.readdirSync(dirPath)
      const jsonFiles = files.filter((f) => f.endsWith(".json"))

      for (const file of jsonFiles) {
        const filePath = path.join(dirPath, file)
        const content = fs.readFileSync(filePath, "utf-8")
        const agent = JSON.parse(content)

        if (agent.id === id) {
          found = true
          oldFilePath = filePath
          oldDateDir = dateDir
          agentData = agent
          break
        }
      }

      if (found) break
    }

    if (!found) {
      return NextResponse.json(
        { success: false, error: "Agent not found" },
        { status: 404 },
      )
    }

    // 更新数据
    const updatedAgent = {
      ...agentData,
      name: name || agentData.name,
      components: components !== undefined ? components : agentData.components,
      edges: edges !== undefined ? edges : agentData.edges,
      updatedAt: new Date().toISOString().split("T")[0],
    }

    // 如果名称改变了，需要重命名文件
    if (name && name !== agentData.name) {
      const newFileName = generateFileName(name)
      const newFilePath = path.join(AGENT_DIR, oldDateDir, newFileName)

      // 删除旧文件
      fs.unlinkSync(oldFilePath)

      // 写入新文件
      fs.writeFileSync(newFilePath, JSON.stringify(updatedAgent, null, 2), "utf-8")
    } else {
      // 只更新内容
      fs.writeFileSync(oldFilePath, JSON.stringify(updatedAgent, null, 2), "utf-8")
    }

    return NextResponse.json({
      success: true,
      data: updatedAgent,
      message: "Agent updated successfully",
    })
  } catch (error) {
    console.error("Error updating agent:", error)
    return NextResponse.json(
      { success: false, error: "Failed to update agent" },
      { status: 500 },
    )
  }
}

// DELETE - 删除 Agent
export async function DELETE(request: NextRequest) {
  try {
    ensureBaseDirectoryExists()

    const searchParams = request.nextUrl.searchParams
    const id = searchParams.get("id")

    if (!id) {
      return NextResponse.json(
        { success: false, error: "Agent ID is required" },
        { status: 400 },
      )
    }

    const dateDirs = getAllDateDirectories()
    let found = false

    for (const dateDir of dateDirs) {
      const dirPath = path.join(AGENT_DIR, dateDir)
      const files = fs.readdirSync(dirPath)
      const jsonFiles = files.filter((f) => f.endsWith(".json"))

      for (const file of jsonFiles) {
        const filePath = path.join(dirPath, file)
        const content = fs.readFileSync(filePath, "utf-8")
        const agent = JSON.parse(content)

        if (agent.id === id) {
          fs.unlinkSync(filePath)
          found = true
          break
        }
      }

      if (found) break
    }

    if (!found) {
      return NextResponse.json(
        { success: false, error: "Agent not found" },
        { status: 404 },
      )
    }

    return NextResponse.json({
      success: true,
      message: "Agent deleted successfully",
    })
  } catch (error) {
    console.error("Error deleting agent:", error)
    return NextResponse.json(
      { success: false, error: "Failed to delete agent" },
      { status: 500 },
    )
  }
}
